

package com.shiku.imserver.hander;

import com.shiku.imserver.common.ImSessionContext;

import java.nio.ByteBuffer;

import org.tio.core.ChannelContext;
import org.tio.core.GroupContext;
import org.tio.core.exception.AioDecodeException;
import org.tio.core.intf.Packet;
import org.tio.server.intf.ServerAioHandler;

public class ImServerHandler implements ServerAioHandler {
    public ImServerHandler() {
    }

    @Override
    public void handler(Packet packet, ChannelContext channelContext) throws Exception {
        ImSessionContext imSessionContext = (ImSessionContext) channelContext.getAttribute();
        AbstractProtocolHandler handler = (AbstractProtocolHandler) imSessionContext.getProtocolHandler();
        if (handler != null) {
            handler.handler(packet, channelContext);
        }

    }

    @Override
    public ByteBuffer encode(Packet packet, GroupContext groupContext, ChannelContext channelContext) {
        ImSessionContext imSessionContext = (ImSessionContext) channelContext.getAttribute();
        AbstractProtocolHandler handler = (AbstractProtocolHandler) imSessionContext.getProtocolHandler();
        return handler != null ? handler.encode(packet, groupContext, channelContext) : null;
    }

    @Override
    public Packet decode(ByteBuffer buffer, int limit, int position, int readableLength, ChannelContext channelContext) throws AioDecodeException {
        ImSessionContext imSessionContext = (ImSessionContext) channelContext.getAttribute();
        AbstractProtocolHandler handler = (AbstractProtocolHandler) imSessionContext.getProtocolHandler();
        if (handler != null) {
            return handler.decode(buffer, limit, position, readableLength, channelContext);
        } else {
            throw new AioDecodeException("不支持的协议类型,无法找到对应的协议解码器!");
        }
    }
}
